@echo off

cls

SETLOCAL enabledelayedexpansion

set burn_tool=%~dp0tools\upgrade_tool.exe

REM set images_path=%~dp0images
set images_path=D:\RKDevtool\images\

call :check_tool
call :check_burn_mode
call :burn_image
goto :EOF

:check_tool
if not exist %burn_tool% (
    echo Error: upgrade_tool.exe not found
    goto :quit
)
for /f %%i in ('hdc -v') do (
    set hdc_exit=%%i
)
if "%hdc_exit%"=="" (
    echo hdc not found!
	goto :quit
)
exit /B 0

:check_burn_mode
set flag=0
for /f "delims=" %%i in ('%burn_tool% LD') do (
    set tmp=%%i
    if "!tmp:~-8,-1!"=="Maskrom" (
        echo Maskrom mode, change to loader mode, please wait...
        set flag=1
    ) else if "!tmp:~-4,-1!"=="none" (
        echo Not found device!
        goto :quit
    ) else if "!tmp:~-7,-1!"=="Loader" (
       echo Loader burn mode
    )
)
if %flag%==1 (
    for /f %%i in ('hdc kill') do echo %%i
    TIMEOUT /NOBREAK 5
    for /f %%i in ('hdc start') do echo %%i
    TIMEOUT /NOBREAK 5
    for /f %%i in ('hdc shell reboot loader') do echo %%i
    TIMEOUT /NOBREAK 10
    call :check_burn_mode
)
exit /B 0

:burn_image
del test.log
echo start burn image...
for /f "tokens=* delims=" %%i in ('%burn_tool% UL %images_path%\MiniLoaderAll.bin -noreset') do (
    echo %%i >> test.log
    set tmp=%%i
    if "!tmp:~0,-1!"=="Upgrade loader ok." (
        echo MiniLoaderAll.bin Upgrade loader ok.
    )
)
for /f "tokens=* delims=" %%i in ('%burn_tool% DI -p %images_path%\parameter.txt') do (
    echo %%i >> test.log
    set tmp=%%i
    if "!tmp:~0,-1!"=="Write gpt ok." (
         echo parameter.txt Upgrade loader ok.
    )
 )
for %%i in (uboot resource boot_linux ramdisk system vendor userdata) do (
     for /f "tokens=* delims=" %%j in ('%burn_tool% DI -%%i %images_path%\%%i.img') do (
        echo %%j >> test.log
        set tmp=%%j
        if "!tmp:~0,-1!"=="Download image ok." (
            echo %%i.img Upgrade loader ok.
        )
    )
)
echo end burn image...
for /f "tokens=* delims=" %%i in ('%burn_tool% RD') do echo %%i >> test.log
echo reboot device...
exit /B 0

:quit
pause
exit
goto :EOF